package com.sdhs.projectstart.service.impl;


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.JsonObject;
import com.sdhs.common.utils.AESUtils;
import com.sdhs.common.utils.SafetyUtil;
import com.sdhs.initdata.domain.SfPerson;
import com.sdhs.initdata.mapper.InitDataMapper;
import com.sdhs.safetymanage.domain.SafetyProject;
import com.sdhs.safetymanage.service.ISafetyProjectService;
import com.sdhs.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sdhs.businessfile.domain.BusinessFile;
import com.sdhs.businessfile.service.IBusinessFileService;
import com.sdhs.common.core.domain.entity.SysUser;
import com.sdhs.common.core.domain.event.ProcessEvent;
import com.sdhs.common.enums.BusinessStatusEnum;
import com.sdhs.common.enums.BusinessTypeEnum;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.common.utils.StringUtils;
import com.sdhs.myproject.domain.GcMyprojectInformation;
import com.sdhs.myproject.service.IGcMyprojectInformationService;
import com.sdhs.projectstart.domain.ProjectDept;
import com.sdhs.projectstart.mapper.ProjectDeptMapper;
import com.sdhs.projectstart.service.IProjectDeptService;
import com.sdhs.system.mapper.SysUserMapper;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 项目组信息 服务层
 *
 * @author ww
 */
@Service
public class ProjectDeptServiceImpl implements IProjectDeptService {
    @Autowired
    private ProjectDeptMapper projectDeptMapper;

    @Autowired
    private IBusinessFileService businessFileService;
    
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private IGcMyprojectInformationService gcInformationService;
    @Autowired
    private ISafetyProjectService safetyProjectService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private InitDataMapper initDataMapper;
    @Override
    public List<ProjectDept> selectProjectDeptList(ProjectDept proDept) {
        return projectDeptMapper.selectProjectDeptList(proDept);
    }

    /**
     * 查询参数配置信息
     *
     * @param id 参数配置ID
     * @return 参数配置信息
     */
    @Override
    public ProjectDept selectProjectDeptById(Long id) {
        ProjectDept projectDept = projectDeptMapper.selectProjectDeptById(id);
        String otherOwner = projectDept.getOtherOwner();
        if (StringUtils.isNotEmpty(otherOwner)) {
        	String[] otherOwnerArray = otherOwner.split(",");
        	List<String> userNameList = Arrays.asList(otherOwnerArray);
        	SysUser sysUser = new SysUser();
        	sysUser.setUserNameList(userNameList);
        	List<SysUser> userList = userMapper.queryUserList(sysUser);
        	if (CollectionUtil.isNotEmpty(userList)) {
        		List<String> nickNameList = userList.stream().map(user -> user.getNickName()).collect(Collectors.toList());
        		String otherOwnerName = String.join(",", nickNameList);
        		projectDept.setOtherOwnerName(otherOwnerName);
        	}
        }
        List<BusinessFile> businessFiles = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_PROJECT_DEPT_FORMATION.getCode(), String.valueOf(id));
        projectDept.setFileList(businessFiles);
        return projectDept;
    }


    /**
     * 新增保存项目组信息
     *
     * @param proDept 项目组数据信息
     * @return 结果
     */
    @Override
    public ProjectDept insertProjectDept(ProjectDept proDept) {
    	String username = SecurityUtils.getUsername();
        proDept.setCreateBy(username);
        if(StringUtils.isEmpty(proDept.getManager())) {
        proDept.setManager(username);
        }
        projectDeptMapper.insertProjectDept(proDept);
        handler(proDept.getId(), proDept);
        return proDept;
    }

    /**
     * 修改项目组信息
     *
     * @param proDept 项目组数据信息
     * @return 结果
     */
    @Override
    public int updateProjectDept(ProjectDept proDept) {
    	proDept.setUpdateBy(SecurityUtils.getUsername());
        int i = projectDeptMapper.updateProjectDept(proDept);
        handler(proDept.getId(), proDept);
        GcMyprojectInformation gcMyprojectInformation = gcInformationService.selectDeptByProject(proDept.getProjectId());
        /*推送安全项目开始*/
        if (gcMyprojectInformation!=null){
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("engineeringId", proDept.getProjectId()); //项目id
            jsonObject.addProperty("type", "update"); //类型
            jsonObject.addProperty("pmUserId", gcMyprojectInformation.getUserId()); //项目经理
            jsonObject.addProperty("pmLink", gcMyprojectInformation.getPmLink()); //项目经理电话
            jsonObject.addProperty("safePersonUserId", gcMyprojectInformation.getSafePersonId()); //项目安全员
            jsonObject.addProperty("safePersonLink", gcMyprojectInformation.getSafePersonLink()); //项目安全员电话
            try {
                String jsonData = jsonObject.toString(); // 直接转为JSON字符串
                String encryptedData = AESUtils.encrypt(jsonData);
                /*推送安全接口*/
                SafetyUtil.pushUrl(encryptedData);
            } catch (JsonProcessingException e) {
                System.err.println("JSON序列化失败: " + e.getMessage());
                throw new RuntimeException(e);
            } catch (Exception e) {
                System.err.println("加密失败: " + e.getMessage());
                throw new RuntimeException(e);
            }
        }
        /*推送安全项目结束*/
        return i;
    }

    @Override
    public int deleteProjectDeptByIds(Long[] ids) {
        return projectDeptMapper.deleteProjectDeptByIds(ids);
    }

    /**
     * 保存联合数据
     * 保存合同附件
     */
    public void handler(Long id, ProjectDept proDept) {
        // 保存合同附件
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_PROJECT_DEPT_FORMATION.getCode(), String.valueOf(id), proDept.getFileList());
        SafetyProject safetyProject= new SafetyProject();
        //根据项目id查询安全项目id，项目经理
         GcMyprojectInformation gcMyprojectInformation = gcInformationService.selectGcMyProjectInformationByProject(proDept.getProjectId());
        safetyProject.setId(gcMyprojectInformation.getSafetyProjectId());
        safetyProject.setSafePerson(gcMyprojectInformation.getSecureId()); //项目安全员，人员表id
        safetyProject.setSafePersonLink(gcMyprojectInformation.getSafePersonLink()); //项目安全员电话
        if(gcMyprojectInformation.getId()!=null){
            safetyProject.setPm(gcMyprojectInformation.getId());
            safetyProject.setPmLink(gcMyprojectInformation.getPmLink());
        }else{
            SfPerson sfPerson = new SfPerson();
            SysUser sysUser = userService.selectUserById(gcMyprojectInformation.getUserId());
            sfPerson.setDelFlag(Long.valueOf(sysUser.getDelFlag()));
            sfPerson.setType("2");
            sfPerson.setName(sysUser.getNickName());
            sfPerson.setSex(sysUser.getSex());
            sfPerson.setIdNumber(sysUser.getIdCard());
            sfPerson.setLinkNumber(sysUser.getPhonenumber());
            sfPerson.setDeptId(sysUser.getDeptId());
            sfPerson.setIsUser("Y");
            sfPerson.setUserId(sysUser.getUserId());
            sfPerson.setUserName(sysUser.getUserName());
            initDataMapper.insertSfPerson(sfPerson) ;
            safetyProject.setPm(sfPerson.getId());
        }

        safetyProjectService.updateSafetyProject(safetyProject);
    }
    /**
     项目部组建审批监听
     */
    @org.springframework.context.event.EventListener(condition = "#processEvent.key.startsWith('project_department_set_up')")
    public void processHandler(ProcessEvent processEvent) {

        // 已完成（已通过）
        if (BusinessStatusEnum.FINISH.getStatus().equals(processEvent.getStatus())) {
            String businessKey = processEvent.getBusinessKey();
            ProjectDept projectDept = projectDeptMapper.selectDeptInstanceId(businessKey);
            GcMyprojectInformation gcMyprojectInformation = new GcMyprojectInformation();
            gcMyprojectInformation.setId(projectDept.getProjectId());
            gcMyprojectInformation.setProjectStatus("2");
            /*修改项目状态为实施中*/
            gcInformationService.updateGcMyProject(gcMyprojectInformation);
        }

    }
}
